package encrypt

import (
	"crypto/md5"
	//	"crypto/rand"
	//	"encoding/base64"
	"encoding/hex"
	//	"io"

	"reflect"
	//	"strconv"
	"strings"
	"time"

	"github.com/satori/go.uuid"
	//	"github.com/astaxie/beego"
)

//把字符串转换为md5方法
func Md5(s string) string {
	h := md5.New()
	h.Write([]byte(s))
	return hex.EncodeToString(h.Sum(nil))
}

/**
*把字节转化为MD5字符串
 */
func MD5(b []byte) string {
	vCrypto := md5.New()
	vCrypto.Write(b)
	return hex.EncodeToString(vCrypto.Sum(nil))
}

/*
*加密用户密码
 */
func EncodeUserPwd(uname, pwd string) string {
	return MD5([]byte(strings.Join([]string{uname, "$user$", pwd}, "")))
}

/*
*加密客户密码
 */
func EncodeMemberPwd(uname, pwd string) string {
	return MD5([]byte(strings.Join([]string{uname, "$member$", pwd}, "")))
}

/*
*加密token
 */
func EncodeToken(sessionid string) string {
	timez := time.Now().String()
	return MD5([]byte(strings.Join([]string{sessionid, "$token$", timez}, "")))
}

/*
*加密商户密码
 */
func EncodeStorerPwd(uname, pwd string) string {
	return MD5([]byte(strings.Join([]string{uname, "$storer$", pwd}, "")))
}

/*
*stuct 转 map
 */
func Struct2Map(obj interface{}) map[string]interface{} {
	t := reflect.TypeOf(obj)
	v := reflect.ValueOf(obj)

	var data = make(map[string]interface{})
	for i := 0; i < t.NumField(); i++ {
		data[t.Field(i).Name] = v.Field(i).Interface()
	}
	return data
}

//获取Guid方法，获取48位uuid
func GetGuid() string {
	//	b := make([]byte, 48)

	//	if _, err := io.ReadFull(rand.Reader, b); err != nil {
	//		return ""
	//	}
	//	return MD5([]byte(base64.URLEncoding.EncodeToString(b)))
	return uuid.NewV1().String()
}
